package mymodule

import (
	"fmt"

	"simplemath"

	"github.com/yuin/gopher-lua"
)

func Loader(L *lua.LState) int {
	// register functions to the table
	mod := L.SetFuncs(L.NewTable(), exports)
	// register other stuff
	L.SetField(mod, "name", lua.LString("value"))

	// returns the module
	L.Push(mod)
	return 1
}

var exports = map[string]lua.LGFunction{
	"myfunc": myfunc,
	"add":    add,
	"sqrt":   sqrt,
}

func myfunc(L *lua.LState) int {
	fmt.Println(L.Get(1), L.Get(2))
	return 0
}

func add(L *lua.LState) int {
	lv := L.ToNumber(1) + L.ToNumber(2)
	L.Push(lv)
	return 1
}

func sqrt(L *lua.LState) int {
	lv := simplemath.Sqrt(L.ToInt(1))

	L.Push(lua.LNumber(lv))

	return 1
}
